<?php

namespace addons\shopro\service\user;

use app\admin\model\shopro\commission\Agent;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\Performance;
use app\admin\model\shopro\user\User as UserModel;

class User
{
    /**
     * @name 追加消费金额
     * @param int|object $user 会员对象或会员ID
     * @param float $amount 变更金额
     * @return boolean
     */
    public static function consume($user, $amount)
    {
        // 判断金额
        if ($amount == 0) {
            return false;
        }

        // 判断用户
        if (is_numeric($user)) {
            $user = UserModel::getById($user);
        }
        if (!$user) {
            dump("未找到用户");
            return false;
            //error_stop('未找到用户');
        }


        // 更新会员余额信息
        $user->setInc('total_consume', $amount);

        return true;
    }

    /**
     * @name 追加pv值--业绩
     * @param int|object $user 会员对象或会员ID
     * @param float $amount 变更金额
     * @return boolean
     */
    public static function consumePv($user, $order)
    {
        // 判断金额
        if ($order['pv_price'] == 0) {
            return false;
        }

        // 判断用户
        if (is_numeric($user)) {
            $user = UserModel::getById($user);
        }
        if (!$user) {
            dump("未找到用户");
            return false;
            //error_stop('未找到用户');
        }
        // 更新会员累计消费（pv值）信息
        $user->setInc('total_consume_pv', $order['pv_price']);

        $user_agnet = \app\admin\model\shopro\user\User::with(['agent' => function ($query) {
            return $query->with('level_info');
        }])
            ->where(["id" => $user["id"]])->find();//查找下单用户
        $time = time();
        $data = [];
        $configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
        //2023-12-29 修改 会员及以上等级业绩算自己
        if (!empty($user_agnet["agent"]) && $user_agnet["agent"]["level"] > 1) {
            $user->setInc('performance', $order['pv_price']);
            $data_self = [
                "order_id" => $order["id"],
                "order_details" => json_encode($order),
                "money" => $order["pv_price"],
                "user_id" => $user["id"],
                "createtime" => $time,
                "level" => $user_agnet["agent"]["level"] ?? 0,
                "is_dividend" => 0,
                "is_self" => 1,
            ];
            if ($user_agnet["level"] >= $configs["level"] && $user["agent"][$configs["level"]] >= 2) {
                //有资格参与
                $data_self["is_dividend"] = 1;
            }
            $data[] = $data_self;
        }
        //新增业绩记录
        if (!empty($user["parent_user_id"])) {
            $ids = self::getParent($user["parent_user_id"]);
            $parent_data = [];
            if (!empty($ids)) {
                foreach ($ids as $k => $v) {
                    $commiss = Agent::where(["user_id" => $v])->find();
                    $parent_data[$k] = [
                        "order_id" => $order["id"],
                        "order_details" => json_encode($order),
                        "money" => $order["pv_price"],
                        "user_id" => $v,
                        "createtime" => $time,
                        "level" => $commiss["level"] ?? 0,
                    ];
                    if ($commiss["level"] >= $configs["level"] && isset($commiss["child_agent_level_market"][$configs["level"]]) && $commiss["child_agent_level_market"][$configs["level"]] >= 2) {
                        //有资格参与
                        $parent_data[$k]["is_dividend"] = 1;
                    }
                    $parent = UserModel::getById($v);
                    // 更新会员累计消费（pv值）信息
                    $parent->setInc('performance', $order['pv_price']);
                }
            }
            $data = array_merge($data, $parent_data);
        }
        if (!empty($data)) {
            $PerformanceModel = new Performance();
            $res = $PerformanceModel->saveAll($data);
        }
        return true;
    }

    /**
     * 查找所有有关上级
     * */
    public static function getParent($members_id, $arr = [])
    {
        // 无限查询上级
        $members = UserModel::getById($members_id);
        if (!empty($members)) {
            if (empty($arr)) {
                $arr[] = $members["id"];
            }
            if (!empty($members["parent_user_id"])) {
                $rows = UserModel::field("id")->where(["id" => $members["parent_user_id"]])->find();
                $rows2 = [];
                if (!empty($rows)) {
                    if (in_array($rows["id"], $arr)) {
                        return $arr;
                    } else {
                        $rows2 = $rows["id"];
                    }
                }
                array_push($arr, $rows2);
                if ($rows['id'] == 0) {
                    return $arr;
                } else {
                    return self::getParent($rows['id'], $arr);
                }
            }
        }
        return $arr;
    }

    /**
     * @name 扣除--业绩
     * @param int|object $user 会员对象或会员ID
     * @param float $amount 变更金额
     * @return boolean
     */
    public static function deductConsumePv($user, $order)
    {
        // 判断金额
        if ($order['pv_price'] == 0) {
            return false;
        }
        // 更新会员累计消费（pv值）信息
        $user->setDec('total_consume_pv', $order['pv_price']);
        $user->setDec('total_consume', $order['pay_fee']);
        $time = time();
        $performance = Performance::where(["order_id" => $order["id"]])->select();
        if (!empty($performance)) {
            //开始退还业绩
            foreach ($performance as $k => $v) {
                $parent_data[$k] = [
                    "order_id" => $order["id"],
                    "order_details" => json_encode($order),
                    "money" => -$order["pv_price"],
                    "user_id" => $v["user_id"],
                    "createtime" => $time,
                    "level" => $v["level"] ?? 0,
                    "memo" => "退货退回业绩",
                    "is_dividend" => $v["is_dividend"],
                    "is_self" => $v["is_self"],
                ];
                $parent = UserModel::getById($v["user_id"]);
                // 更新会员累计消费（pv值）信息
                $parent->setDec('performance', $order['pv_price']);
            }
            if (!empty($parent_data)) {
                $PerformanceModel = new Performance();
                $PerformanceModel->saveAll($parent_data);
            }
        }
        return true;
    }


}
